<template>
  <div class="app-container-flex">
    <NewFullScreen
      v-model="showDialog"
      :title="title"
      :needReturn="!flowFormType"
    >
      <template v-slot:full-button>
        <el-button
          @click="saveAndSubmit()"
          :disabled="!canSave"
          v-if="
            !tableRow.id &&
            $permission('adjustPrice:saveAndSubmit') &&
            !flowFormType
          "
          >保存并提交</el-button
        >
        <el-button v-if="!flowFormType" @click="save()" :disabled="!canSave"
          >保存</el-button
        >
      </template>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <!-- form -->
          <page-form
            ref="adjustPriceModifyForm"
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="formInfo.ref"
            :disabled="formInfo.disabled"
            :data="formInfo.data"
            :field-list="formInfo.fieldList"
            :rules="formInfo.rules"
            :label-width="formInfo.labelWidth"
          >
            <template v-slot:form-supplierName>
              <el-input
                class="not-mongolia"
                type="input"
                placeholder="请选择供应商"
                :disabled="true"
                v-model="formInfo.data.supplierName"
              >
                <template #append>
                  <el-icon @click="_selectSupplier"><MoreFilled /></el-icon>
                </template>
              </el-input>
            </template>
            <template v-slot:form-fileUrlList>
              <UploadImg
                v-model:value="formInfo.data.fileUrlList"
                :action="action"
                :list-type="'text'"
                :file-type="fileType"
                :fileData="formInfo.data.fileUrlList"
                :response-fn="handleResponse"
              />
            </template>
          </page-form>
        </div>
      </div>

      <div class="model-panel">
        <div class="model-panel-title">
          <Tooltip :text="$t('detailInfo')" />
        </div>
        <div class="model-panel-body">
          <!-- 条件栏 -->
          <page-filter
            v-model:query="filterInfo.query"
            :filter-list="filterInfo.list"
          >
            <template v-slot:filter-batchPriceAdjustment>
              批量调价：
              <el-input-number
                :min="systemConfig.product_price_can_be_zero ? 0 : 1"
                controls-position="right"
                :precision="systemConfig.price_precision"
                :max="999999999999999"
                style="width: 200px"
                placeholder="请输入调价后价格"
                v-model="filterInfo.query.batchPriceAdjustment"
              ></el-input-number>
            </template>
            <template v-slot:filter-adjustReason>
              调价原因：
              <el-input
                style="width: 200px"
                placeholder="请输入调价原因"
                v-model="filterInfo.query.adjustReason"
                clearable
              ></el-input>
            </template>
          </page-filter>
          <div class="flex_full_item">
            <el-form :model="tableInfo" ref="tableForm" style="width: 100%">
              <!-- 表格 -->
              <page-table
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :api="tableInfo.api"
                :pager="false"
                :tabIndex="true"
                :isRowClickSelect="true"
                :query="filterInfo.query"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :isDynamic="true"
                @handleEvent="handleEvent"
              >
                <template v-slot:col-afterPrice="scope">
                  <el-form-item
                    :prop="`data.${scope.$index}[afterPrice]`"
                    :rules="
                      scope.$index >= 0
                        ? [
                            {
                              validator: $validate.positiveMoneyZero,
                              trigger: 'blur',
                            },
                          ]
                        : []
                    "
                  >
                    <el-input-number
                      v-model="scope.row.afterPrice"
                      controls-position="right"
                      style="width: 100%"
                      :precision="systemConfig.price_precision"
                      :step="1"
                      :min="0"
                      :max="999999999999999"
                      @change="
                        changePrice($event, `data.${scope.$index}.afterPrice`)
                      "
                    />
                    <p
                      style="color: red"
                      v-if="
                        scope.row.isLimitPrice == 1 &&
                        scope.row.afterPrice > scope.row.purchaseLimitPrice
                      "
                    >
                      超过产品限价:{{ scope.row.purchaseLimitPrice }}
                    </p>
                  </el-form-item>
                </template>
                <template v-slot:col-adjustReason="scope">
                  <el-form-item :prop="`data.${scope.$index}[adjustReason]`">
                    <el-input
                      placeholder="请输入调价原因"
                      v-model="scope.row.adjustReason"
                      clearable
                    ></el-input>
                  </el-form-item>
                </template>
              </page-table>
            </el-form>
          </div>
          <select-supplier
            v-if="selectSupplierInfo.visible"
            v-model:show-dialog="selectSupplierInfo.visible"
            :check-box="false"
            :highlightRow="true"
            :query="selectSupplierInfo.query"
            @callback="selectSupplierCallback"
          />

          <select-supplier-product
            v-if="selectSupplierProductInfo.visible"
            v-model:show-dialog="selectSupplierProductInfo.visible"
            :query="selectSupplierProductInfo.query"
            @callback="selectSupplierProductCallback"
          />
        </div>
      </div>
    </NewFullScreen>
  </div>
</template>

<script setup name="adjustPriceModify">
import {
  getAdjustPriceOrder,
  getAdjustPriceOrderDetailsAll,
  createAdjustPriceOrder,
  createAdjustPriceOrderAndSave,
  updateAdjustPriceOrder,
  submitAdjustPriceOrder,
} from '../../../api/purch'
import axios from 'axios'
import { getCustomizeSetting } from '@/api/customize'
import utils from '@/common/js/utils'

const { proxy } = getCurrentInstance()
const emit = defineEmits()

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  tableRow: {
    type: Object,
    default() {
      return {}
    },
  },
  title: {
    type: String,
  },
  id: {
    type: Number,
  },
  flowFormType: {
    type: String,
  },
})

const validateEffectiveDate = (rule, value, callback) => {
  const dateNow = new Date(utils.switchTime(new Date(), 'YYYY-MM-DD')).getTime()
  const date = new Date(value).getTime()
  if (date < dateNow) {
    proxy.$message({
      showClose: true,
      duration: 3500,
      message: '生效日期必须要大于等于当前日期',
      type: 'warning',
    })
  } else {
    callback()
  }
}

const fileType = ref([
  'jpg',
  'jpeg',
  'png',
  'pdf',
  'docx',
  'doc',
  'xls',
  'xlsx',
])
const action = ref(axios.defaults.baseURL + '/pub/uploadfile')
const systemConfig = ref(proxy.$store.state.permission.systemConfig)
const formRefs = ref([])
// 过滤相关配置
const filterInfo = reactive({
  query: {
    customizeUserVO: {},
    queryMap: {
      adjustPriceId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.id || props.tableRow.id,
      },
    },
    queryParams: {},
  },
  list: [
    {
      label: '添加产品',
      type: 'button',
      disabled: true,
      event: addProduct,
    },
    {
      label: '删除产品',
      type: 'button',
      disabled: true,
      event: removeProduct,
    },
    { type: 'slot', label: '批量调价', value: 'batchPriceAdjustment' },
    {
      type: 'button',
      label: '批量调价',
      event: batchPriceAdjustmentHandle,
    },
    { type: 'slot', label: '调价原因', value: 'adjustReason' },
    {
      type: 'button',
      label: '调价原因设置',
      event: batchReasonAdjustmentHandle,
    },
  ],
})
//表单相关
const formInfo = reactive({
  ref: null,
  data: {
    supplierName: '',
    supplierId: '',
    fileUrlList: [],
  },
  fieldList: [
    { label: '供应商', value: 'supplierName', type: 'slot' },
    {
      label: '生效日期',
      value: 'effectiveDate',
      type: 'date',
      TimePickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
        },
      },
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
    },
    {
      label: '附件',
      value: 'fileUrlList',
      type: 'slot',
      className: 'not-br',
    },
  ],
  rules: {
    supplierName: [1],
    effectiveDate: [
      { required: true, message: '请选择生效日期', blur: 'change' },
      { validator: validateEffectiveDate, trigger: 'blur' },
    ],
  },
  labelWidth: '120px',
})
// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  api: getAdjustPriceOrderDetailsAll,
  data: [],
  selections: [],
  fieldList: [
    {
      label: '通用名称\n编码\n别名',
      value: 'commonName',
      type: 'slot',
      minWidth: '220px',
    },
    {
      label: '产品类型\n条码类型\n产品分类',
      value: 'type',
      type: 'slot',
      minWidth: '150px',
    },
    {
      label: '是否挂网\n挂网类型\n商品代码',
      value: 'isSunPurchase',
      type: 'slot',
    },
    { label: '规格\n计量单位', value: 'standard', type: 'slot' },
    {
      label: '调价前价格',
      value: 'beforePrice',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
    },
    {
      label: '调价后价格',
      value: 'afterPrice',
      type: 'slot',
      minWidth: '220px',
    },
    {
      label: '调价原因',
      value: 'adjustReason',
      type: 'slot',
      minWidth: '220px',
    },
    {
      label: '证号\n生产厂家',
      value: 'licenseNumber',
      type: 'slot',
      minWidth: '220px',
    },
    // { label: "备注", value: "remark", type: "input" }
  ],
})
const selectSupplierInfo = reactive({
  visible: false,
  query: {
    searchType: 'org',
    searchField: 'supplierId',
    supplierAuth: 'supplierId',
  },
})
const selectSupplierProductInfo = reactive({
  visible: false,
  query: {
    supplierId: '',
    type: 0,
  },
})

const canSave = computed(() => {
  return tableInfo.data.length
})
const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})

watch(
  () => formInfo.data.supplierId,
  (value) => {
    filterInfo.list[0].disabled = !value
  }
)
watch(
  () => tableInfo.selections,
  (value) => {
    filterInfo.list[1].disabled = !value.length
  }
)

let obj = {
  afterPrice: {
    label: '调价后价格',
    value: 'afterPrice',
    type: 'slot',
  },
  adjustReason: {
    label: '调价原因',
    value: 'adjustReason',
    type: 'slot',
  },
}
tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...obj,
})
getCustomize()

function getCustomize() {
  let param = {
    tableKey:
      'AdjustPriceOrderDetail-com.slip.spd.entity.vo.purch.AdjustPriceOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.query.customizeUserVO = data
      let obj = proxy.$fn.setFieldList(tableInfo.fieldList, data.detail, true)
      tableInfo.fieldList = obj.fieldList
      if (props.id || props.tableRow.id) {
        getMain()
        getList()
      }
    }
  })
}
function handleResponse(response, file) {
  return file
}
function changePrice(e, str) {
  proxy.$refs.tableForm.clearValidate(str)
}
// 获取列表
function getList() {
  tableInfo.refresh = Math.random()
}
function getMain() {
  getAdjustPriceOrder(props.id || props.tableRow.id).then((res) => {
    if (res && res.success) {
      let data = res.data.fileUrlList || []
      formInfo.data = res.data
      formInfo.data['fileUrlList'] = data
    }
  })
}
// 搜索
function search() {
  // 重置分页
  tableInfo.initCurpage = Math.random()
  tableInfo.refresh = Math.random()
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = [...data]
      break
    case 'changePrice':
      proxy.$refs.tableForm.clearValidate(data)
      break
  }
}
// flowData 外部流程页面调用
function saveAndSubmit(flowData) {
  save(true, flowData)
}
function save(isSaveAndSubmit, obj = {}) {
  formRefs.value.push(
    proxy.$refs['adjustPriceModifyForm'].$refs['form'],
    proxy.$refs['tableForm']
  )
  proxy.$fn.checkForm(formRefs.value).then(() => {
    const tempBool = tableInfo.data.some((item) => {
      return item.beforePrice === item.afterPrice
    })
    if (tempBool) {
      proxy.$message.warning('调价前价格和调价后价格不能相同,请检查重新输入')
      return
    }
    const data = formInfo.data
    let api = data.id
      ? updateAdjustPriceOrder
      : isSaveAndSubmit === true
      ? createAdjustPriceOrderAndSave
      : createAdjustPriceOrder
    const details = tableInfo.data.filter((row) => row.productId)
    data.details = details
    let flowParams = data
    if (isSaveAndSubmit === true) {
      if (proxy.$route.query.processInstanceId) {
        api = submitAdjustPriceOrder
      }
      flowParams = {
        orderData: flowParams,
        // flowTaskCommentDto和processDefinitionKey为审批流程需要传递的参数
        flowTaskCommentDto: { approvalType: 'submit' },
        processDefinitionKey: 'adjustOrder',
        processInstanceId: obj.processInstanceId,
        taskId: obj.taskId,
      }
    }
    api(flowParams).then((resp) => {
      if (resp && resp.success) {
        showDialog.value = false
        emit('returnModify', false)
      }
    })
  })
}
//选择供应商
function _selectSupplier() {
  selectSupplierInfo.visible = true
}
function selectSupplierCallback(data) {
  tableInfo.data = []
  formInfo.data.supplierId = data.supplierId
  formInfo.data.supplierName = data.supplierName
}
//添加产品
function addProduct() {
  selectSupplierProductInfo.query.productIdNotIn = tableInfo.data
    .map((row) => row.productId)
    .toString()
  selectSupplierProductInfo.query.supplierId = formInfo.data.supplierId
  selectSupplierProductInfo.visible = true
}
function selectSupplierProductCallback(rows) {
  if (rows) {
    rows.forEach((row) => (row.beforePrice = row.price))
    tableInfo.data = rows.concat(tableInfo.data)
  }
}
//删除产品
function removeProduct() {
  tableInfo.data = tableInfo.data.filter(
    (row) => !tableInfo.selections.includes(row)
  )
}
function batchReasonAdjustmentHandle() {
  let reason = filterInfo.query.adjustReason
  if (reason) {
    if (tableInfo.selections.length) {
      tableInfo.selections.forEach((row) => {
        row['adjustReason'] = reason
      })
    } else {
      proxy.$message({
        message: '请选择需批量调价原因的产品！',
        type: 'warning',
        duration: 3500,
        showClose: true,
      })
    }
  }
}
function batchPriceAdjustmentHandle() {
  let num = filterInfo.query.batchPriceAdjustment
  if (num != undefined && num >= 0) {
    if (tableInfo.selections.length) {
      tableInfo.selections.forEach((row) => {
        row['afterPrice'] = num
        tableInfo.data.forEach((item, index) => {
          if (row.id === item.id) {
            proxy.$refs.tableForm.clearValidate(`data.${index}[afterPrice]`)
          }
        })
      })
    } else {
      proxy.$message({
        message: '请选择需批量调价的产品！',
        type: 'warning',
        duration: 3500,
        showClose: true,
      })
    }
  }
}
// 名称不要做改变，在流程引擎中需要通过refs进行调用
defineExpose({
  save,
  saveAndSubmit,
})
</script>

<style scoped></style>
